package cn.mulanbay.auth.config;

import cn.mulanbay.business.config.CacheConfig;
import cn.mulanbay.business.handler.HandlerManager;
import cn.mulanbay.business.handler.MessageHandler;
import cn.mulanbay.business.handler.PasswordHandler;
import cn.mulanbay.business.handler.ThreadPoolHandler;
import cn.mulanbay.common.json.CustomObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

/**
 * SpringMVC相关配置
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@Configuration
public class WebConfig {

    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);

    /**
     * 解决value设置默认值后无法注入问题
     * @return
     */
    @Primary
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setIgnoreUnresolvablePlaceholders(true);
        return configurer;
    }

    /**
     * 资源文件管理，支持国际化
     *
     * @return
     */
    @Bean
    public ReloadableResourceBundleMessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("utf-8");
        messageSource.setCacheSeconds(120);
        return messageSource;
    }

    /**
     * json处理类
     * @return
     */
    @Primary
    @Bean
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper objectMapper() {
        logger.debug("初始化objectMapper");
        ObjectMapper objectMapper = new CustomObjectMapper();
        return objectMapper;
    }

    /**
     * 资源文件配置的处理
     * @return
     */
    @Bean
    public MessageHandler messageHandler() {
        return new MessageHandler();
    }

    /**
     * 密码处理
     * @return
     */
    @Bean
    public PasswordHandler passwordHandler() {
        return new PasswordHandler();
    }

    /**
     * 线程池处理
     * @return
     */
    @Bean
    public ThreadPoolHandler threadPoolHandler() {
        return new ThreadPoolHandler();
    }

    /**
     * 处理器管理类
     * @return
     */
    @Bean
    public HandlerManager handlerManager() {
        return new HandlerManager();
    }

    /**
     * 缓存配置
     */
    @Configuration
    public class MyCacheConfig extends CacheConfig{

    }
}
